package com.mirror.tk.api.controller.user;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.collect.Maps;
import com.mirror.tk.api.common.Constant;
import com.mirror.tk.api.common.support.JwtFace;
import com.mirror.tk.api.common.support.JwtUser;
import com.mirror.tk.api.controller.CommonController;
import com.mirror.tk.api.utils.PwdUtil;
import com.mirror.tk.core.log.annotation.Log;
import com.mirror.tk.core.module.sms.service.ValidateCodeService;
import com.mirror.tk.core.module.user.domain.User;
import com.mirror.tk.core.module.user.dto.UserDto;
import com.mirror.tk.core.module.user.service.UserService;
import com.mirror.tk.core.sms.service.SendTemplateSmsService.TEMPLATE_CODE;
import com.mirror.tk.framework.common.exception.BusinessException;
import com.mirror.tk.framework.common.web.support.JsonEntityResult;
import com.mirror.tk.framework.common.web.support.JsonResult;
import com.mirror.tk.framework.utils.Collections3;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(value = "用户相关API", description = "提供用户相关操作（该接口需要授权）")
@RestController
public class UserController extends CommonController {

	@Resource
	private ValidateCodeService validateCodeService;
	@Resource
	private UserService userService;
	
	@ApiOperation(value = "找回密码", notes = "找回密码")
	@Log(module="User", moduleName="用户", action="findPwd", actionName="找回密码", tag="api")
	@RequestMapping(value = "findPwd", method = RequestMethod.POST)
	public JsonResult findPwd(HttpServletRequest request, 
			@ApiParam(value = "电话号码", required = true)@RequestParam(value = "phone", required = true)String phone,
			@ApiParam(value = "验证码", required = true)@RequestParam(value = "code", required = true)String code,
			@ApiParam(value = "短信类型", required = true)@RequestParam(value = "type", required = true)Integer type,
			@ApiParam(value = "新密码", required = true)@RequestParam(value = "newPwd", required = true)String newPwd){
		JsonResult result = new JsonResult(false);
		if(validateCodeService.vaildateCode(phone, TEMPLATE_CODE.getCode(TEMPLATE_CODE.retakePwd.getCode()), code, true)){
			User user = userService.getUserByPhone(phone);
			user.setPassword(newPwd);
			PwdUtil.entryptPassword(user);
			user.setUpdateTime(new Date());
			try {
				userService.update(user);
			} catch (Exception e) {
				result.setCode(Constant.Global.FAIL);
				result.setMessage(Constant.UserMassage.USER_FIND_PWD_FAIL);
				return result;
			}
			result.setSuccess(true);
			result.setCode(Constant.Global.SUCCESS);
			result.setMessage(Constant.UserMassage.USER_FIND_PWD_SUCCESS);
			return result;
		}
		result.setCode(Constant.Global.FAIL);
		result.setMessage(Constant.Global.ILLEGAL_ACCESS);
		return result;
	}
	
	@ApiOperation(value = "注册", notes = "注册用户")
	@Log(module="User", moduleName="用户", action="register", actionName="注册", tag="api")
	@RequestMapping(value = "register", method = RequestMethod.POST)
	public JsonEntityResult<JwtUser> register(HttpServletRequest request,
			@ApiParam(value = "电话号码", required = true)@RequestParam(value = "phone", required = true)String phone,
			@ApiParam(value = "验证码", required = true)@RequestParam(value = "code", required = true)String code,
			@ApiParam(value = "密码", required = true)@RequestParam(value = "password", required = true)String password,
			@ApiParam(value = "注册类型", required = true)@RequestParam(value = "type", required = true)Integer type){
		JsonEntityResult<JwtUser> result = new JsonEntityResult<JwtUser>();
		// 验证验证码
		if(!validateCodeService.vaildateCode(phone, TEMPLATE_CODE.getCode(TEMPLATE_CODE.register.getCode()), code, true)){
			result.setCode(Constant.Global.FAIL);
			result.setMessage(Constant.UserMassage.USER_VERIFICATION_CODE_ERROR);
			return result;
		}
		// 再次检查用户名是否存在于系统中
		if(!userisExisted(phone)){
			User user = new User();
			user.setPhone(phone);
			user.setPassword(password);
			user.setStatus(User.STATUS_CONSUMMATE);
			user.setCreateTime(new Date());
			PwdUtil.entryptPassword(user);
			try {
				userService.save(user);
				JwtUser jwtUser = JwtUser.bulider(user);
				result.appendData("Authorization", "Bearer " + JwtFace.setJwtUser(jwtUser));
				result.setEntity(jwtUser);
				result.setSuccess(true);
				result.setCode(Constant.Global.SUCCESS);
				result.setMessage(Constant.UserMassage.USER_REGIEST_SUCCESS);
			} catch (Exception e) {
				logger.error("save fail!error:{}", e.getMessage());
				result.setCode(Constant.Global.FAIL);
				result.setMessage(Constant.UserMassage.USER_REGIEST_FAILE);
			}
			return result;
		}
		result.setCode(Constant.Global.FAIL);
		result.setMessage(Constant.UserMassage.USER_IS_EXISTED);
		return result;
	}
	
	@ApiOperation(value = "更新用户信息", notes = "提供更新用户信息操作")
	@Log(module="User", moduleName="用户", action="updateUser", actionName="更新用户信息", tag="api")
	@RequestMapping(value = "my/user", method = RequestMethod.POST)
	public JsonEntityResult<JwtUser> updateUser(HttpServletRequest request, UserDto user){
		JsonEntityResult<JwtUser> result = new JsonEntityResult<JwtUser>();
		User oUser = userService.get(JwtFace.getJwtUser(request).getId());
		if(null == oUser){
			result.setMessage(Constant.UserMassage.USER_IS_NOT_EXISTED);
			result.setCode(Constant.Global.FAIL);
			return result;
		}
		// 判断是更新用户信息还是提交审核
		if(user.getAge()==null && user.getEmail()==null && user.getSex() == null){
			oUser.setStatus(User.STATUS_CHECK_PENDING);
		}
		if(null != user.getAge()){
			oUser.setAge(user.getAge());
		}
		if(null != user.getIncome()){
			oUser.setIncome(user.getIncome());
		}
		if(null != user.getSex()){
			oUser.setSex(user.getSex());
		}
		if(null != user.getType()){
			oUser.setType(user.getType());
		}
		if(null != user.getAttachment()){
			oUser.setAttachment(user.getAttachment());
		}
		if(null != user.getChannel()){
			oUser.setChannel(user.getChannel());
		}
		if(null != user.getEmail()){
			oUser.setEmail(user.getEmail());
		}
		if(null != user.getQq()){
			oUser.setQq(user.getQq());
		}
		if(null != user.getReason()){
			oUser.setReason(user.getReason());
		}
		if(null != user.getTeamName()){
			oUser.setTeamName(user.getTeamName());
		}
		if(null != user.getUsername()){
			oUser.setUsername(user.getUsername());
		}
		if(null != user.getWechat()){
			oUser.setWechat(user.getWechat());
		}
		oUser.setUpdateTime(new Date());
		try {
			userService.update(oUser);
			JwtUser jwtUser = JwtUser.bulider(oUser);
			result.appendData("Authorization", "Bearer " + JwtFace.setJwtUser(jwtUser));
			result.setSuccess(true);
			result.setEntity(jwtUser);
			result.setCode(Constant.Global.SUCCESS);
			result.setMessage(Constant.UserMassage.USER_UPDATE_SUCCESS);
		} catch (BusinessException e) {
			logger.error("update fail!error:{}", e.getMessage());
			result.setCode(Constant.Global.SUCCESS);
			result.setMessage(Constant.UserMassage.USER_UPDATE_FAIL);
		}
		return result;
	}
	
	@ApiOperation(value = "修改密码", notes = "提供修改密码操作")
	@Log(module="User", moduleName="用户", action="uptatePwd", actionName="修改密码", tag="api")
	@RequestMapping(value = "my/pwd", method = RequestMethod.POST)
	public JsonResult uptatePwd(HttpServletRequest request,
			@ApiParam(value = "旧密码", required = true)@RequestParam(value = "oldPwd", required = true)String oldPwd,
			@ApiParam(value = "新密码", required = true)@RequestParam(value = "newPwd", required = true)String newPwd){
		JsonResult result = new JsonResult(false);
		User user = userService.get(JwtFace.getJwtUser(request).getId());
		if(null == user){
			result.setCode(Constant.Global.FAIL);
			result.setMessage(Constant.UserMassage.USER_IS_NOT_EXISTED);
			return result;
		}
		// 检查原密码是否正确
		boolean b = PwdUtil.validatePassword(user, oldPwd);
		if (b) {
			user.setPassword(newPwd);
			PwdUtil.entryptPassword(user);
			userService.update(user);
			result.setSuccess(true);
			result.setCode(Constant.Global.SUCCESS);
			result.setMessage(Constant.UserMassage.USER_UPDATE_PWD_SUCCESS);
			return result;
		} else {
			result.setCode(Constant.Global.FAIL);
			result.setMessage(Constant.UserMassage.USER_PWD_ERROR);
			return result;
		}
	}
	
	@ApiOperation(value = "检查用户是否存在", notes = "检查用户是否存在")
	@Log(module="User", moduleName="用户", action="isExisted", actionName="检查用户是否存在", tag="api")
	@RequestMapping(value = "isExisted", method = RequestMethod.GET)
	public JsonEntityResult<Boolean> isExisted(HttpServletRequest request, 
			@ApiParam(value = "电话号码", required = true)@RequestParam(value = "phone", required = true)String phone){
		JsonEntityResult<Boolean> result = new JsonEntityResult<Boolean>();
		result.setEntity(!userisExisted(phone));
		result.setCode(Constant.Global.SUCCESS);
		result.setSuccess(true);
		return result;
	}
	
	@ApiOperation(value = "刷新用户状态")
	@Log(module="User", moduleName="用户", action="refresh", actionName="刷新用户状态", tag="api")
	@RequestMapping(value = "my/refresh", method = RequestMethod.GET)
	public JsonEntityResult<JwtUser> refresh(HttpServletRequest request){
		JsonEntityResult<JwtUser> result = new JsonEntityResult<JwtUser>();
		User user = userService.get(JwtFace.getJwtUser(request).getId());
		if(null != user){
			JwtUser jwtUser = JwtUser.bulider(user);
			result.appendData("Authorization", "Bearer " + JwtFace.setJwtUser(jwtUser));
			result.setEntity(jwtUser);
			result.setSuccess(true);
			result.setCode(Constant.Global.SUCCESS);
			return result;
		}
		result.setCode(Constant.Global.FAIL);
		result.setMessage(Constant.UserMassage.USER_IS_NOT_EXISTED);
		return result;
	}
	
	/**
	 * 检查用户是否在系统中存在
	 * @param userName
	 * @return
	 */
	private Boolean userisExisted(String phone){
		if(StringUtils.isNotBlank(phone)){
			Map<String, Object> map = Maps.newHashMap();
			map.put("EQ_phone", phone);
			List<User> userList = userService.query(map, null);
			if(Collections3.isNotEmpty(userList)){
				return true;
			}
		}
		return false;
	}
	
}
